package com.qmth.gkwb.data.sync;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.transaction.Transactional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.qmth.gkwb.data.constant.OrderStatus;
import com.qmth.gkwb.data.document.BaseDoc;
import com.qmth.gkwb.data.document.Education;
import com.qmth.gkwb.data.document.Family;
import com.qmth.gkwb.data.entity.BKBMKMX;
import com.qmth.gkwb.data.entity.BKKS;
import com.qmth.gkwb.data.entity.BKKSJL;
import com.qmth.gkwb.data.entity.BKKSSHGX;
import com.qmth.gkwb.data.entity.BKKSTY;
import com.qmth.gkwb.data.entity.BKKSWY;
import com.qmth.gkwb.data.entity.BKKSYS;
import com.qmth.gkwb.data.document.Order;
import com.qmth.gkwb.data.document.Student;
import com.qmth.gkwb.data.entity.StudentUser;
import com.qmth.gkwb.data.entity.ZFZFD;
import com.qmth.gkwb.data.entity.ZFZFMX;
import com.qmth.gkwb.data.exception.SyncErrorException;
import com.qmth.gkwb.data.repository.BKBMKMXRepo;
import com.qmth.gkwb.data.repository.BKKSJLRepo;
import com.qmth.gkwb.data.repository.BKKSRepo;
import com.qmth.gkwb.data.repository.BKKSSHGXRepo;
import com.qmth.gkwb.data.repository.BKKSTYRepo;
import com.qmth.gkwb.data.repository.BKKSWYRepo;
import com.qmth.gkwb.data.repository.BKKSYSRepo;
import com.qmth.gkwb.data.repository.OrderRepo;
import com.qmth.gkwb.data.repository.StudentRepo;
import com.qmth.gkwb.data.repository.StudentUserRepo;
import com.qmth.gkwb.data.repository.ZFZFDRepo;
import com.qmth.gkwb.data.repository.ZFZFMXRepo;
import com.qmth.pay.chinapay.TransResponse;

/**
 * 同步数据<br />
 * 同步报名数据到主数据库。考生信息、报考信息、支付信息<br />
 * 信息修改后，判断iSyc，如果已经同步，修改提交后，立即执行信息同步任务<br />
 * 考生缴费后，判断iSyc,如果已经同步，缴费后，立即执行支付信息同步任务<br />
 * @author zhengmin
 *
 */
@Service
public class SyncService {

	@Autowired private StudentRepo studentRepo;
	@Autowired private StudentUserRepo userRepo;
	@Autowired private BKKSRepo ksRepo;
	@Autowired private BKBMKMXRepo bmkmxRepo;
	@Autowired private BKKSJLRepo ksjlRepo;
	@Autowired private BKKSSHGXRepo shgxRepo;
	@Autowired private BKKSTYRepo kstyRepo;
	@Autowired private BKKSWYRepo kswyRepo;
	@Autowired private BKKSYSRepo ksysRepo;
	@Autowired private ZFZFDRepo zfdRepo;
	@Autowired private ZFZFMXRepo zfmxRepo;
	@Autowired private OrderRepo orderRepo;
	
	/**
	 * 同步考生信息，更新zc_kszc、bk_ks表的考生信息<br />
	 * 更新bk_bmkmx的考生id和是否已经使用<br />
	 * 插入bk_ksjl、bk_ksshgx和bk_kswy表<br />
	 * 艺术类插入bk_ksys,体育类插入bk_ksty<br />
	 * 插入缴费成功的订单信息<br />
	 * @param student
	 * @throws SyncErrorException 
	 */
	@Transactional
	public boolean syncStudent(Student student) throws SyncErrorException{
		boolean result = false;
		if(student == null){
			throw new SyncErrorException("考生报名信息不存在");
		}
		String examId = student.getExamId();
		//更新zc_kszc
		StudentUser stuUser = userRepo.findOne(examId);
		if(stuUser == null){
			throw new SyncErrorException("注册信息不存在");
		}
		stuUser.setName(student.getName());
		stuUser.setCertino(student.getCertino());
		userRepo.save(stuUser);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		//更新bk_ks
		BKKS ks = ksRepo.findOne(examId);
		if(ks == null){
			throw new SyncErrorException("bk_ks信息不存在");
		}
		ks.setCertino(student.getCertino());
		ks.setName(student.getName());
		if(student.getBirth() != null){
			try {
				ks.setBirth(sdf.parse(student.getBirth()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		ks.setGender(student.getGender());
		if(student.getNation() != null)
			ks.setNationId(student.getNation().getId());
		if(student.getPolity() != null)
			ks.setPolityId(student.getPolity().getId());
		if(student.getCensusProv() != null)
			ks.setCensusProvId(student.getCensusProv().getId());
		if(student.getCensusCity() != null)
			ks.setCensusCityId(student.getCensusCity().getId());
		if(student.getCensusRegion() != null)
			ks.setCensusRegionId(student.getCensusRegion().getId());
		ks.setStuID(student.getStuID());
		if(student.getGrade() != null){
			ks.setGradeId(student.getGrade().getId());
		}
		ks.setTeacher(student.getTeacher());
		if(student.getGradeSchool() != null)
			ks.setGradSchoolId(student.getGradeSchool().getId());
		if(student.getSchoolClass() != null)
			ks.setClassId(student.getSchoolClass().getId());
		if(student.getForeign() != null)
			ks.setForeignId(student.getForeign().getId());
		if(student.getStuType() != null)
			ks.setStuTypeId(student.getStuType().getId());
		ks.setReceive(student.getReceive());		
		ks.setAddress(student.getAddress());
		ks.setZipcode(student.getZipcode());
		if(student.getGraduation() != null)
			ks.setGraduationId(student.getGraduation().getId());
		ks.setSpecial(student.getSpecial());
		ks.setHoner(student.getHonor());
		
		//更新bk_ksjl
		List<Education> edus = student.getEdu();
		
		int ksjl_cnt = 1;
		BKKSJL ksjl = new BKKSJL();
		ksjl.setId(examId);
		for(Education edu : edus){
			Date start = null;
			Date end = null;
			if(edu.getStart() != null){
				try {
					start = sdf.parse(edu.getStart()+"0901");
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(edu.getEnd() != null){
				try {
					end = sdf.parse(edu.getEnd()+"0630");
				} catch (ParseException e) {
					e.printStackTrace();
				}
			}
			if(ksjl_cnt == 1){
				ksjl.setStart1(start);
				ksjl.setEnd1(end);
				ksjl.setSchool1(edu.getSchool());
				ksjl.setPost1(edu.getPost());
				ksjl.setWitness1(edu.getWitness());
			}
			else if(ksjl_cnt == 2){
				ksjl.setStart2(start);
				ksjl.setEnd2(end);
				ksjl.setSchool2(edu.getSchool());
				ksjl.setPost2(edu.getPost());
				ksjl.setWitness2(edu.getWitness());
			}
			else if(ksjl_cnt == 3){
				ksjl.setStart3(start);
				ksjl.setEnd3(end);
				ksjl.setSchool3(edu.getSchool());
				ksjl.setPost3(edu.getPost());
				ksjl.setWitness3(edu.getWitness());
			}
			ksjl_cnt++;
		}
		ksjlRepo.save(ksjl);
		
		//更新bk_ksshgx
		List<Family> families = student.getFamily();
		int fami_cnt = 1;
		BKKSSHGX ksshgx = new BKKSSHGX();
		ksshgx.setId(examId);
		for(Family f : families){
			if(fami_cnt == 1){
				ksshgx.setRelation1(f.getRelation());
				ksshgx.setName1(f.getName());
				ksshgx.setCompany1(f.getCompany());
				ksshgx.setPolity1(f.getPolity());
				ksshgx.setPost1(f.getPost());
				ksshgx.setEduation1(f.getEdu());
			}
			else if(fami_cnt == 2){
				ksshgx.setRelation2(f.getRelation());
				ksshgx.setName2(f.getName());
				ksshgx.setCompany2(f.getCompany());
				ksshgx.setPolity2(f.getPolity());
				ksshgx.setPost2(f.getPost());
				ksshgx.setEduation2(f.getEdu());
			}
			fami_cnt++;
		}
		shgxRepo.save(ksshgx);
		
		//更新bk_kswy
		if(student.getSpokenType() != null){
			BKKSWY kswy = new BKKSWY();
			kswy.setId(examId);
			kswy.setSpokenTypeId(student.getSpokenType().getId());
			kswyRepo.save(kswy);
		}
		
		//更新报名卡为已使用
		BKBMKMX sc = new BKBMKMX();
		sc.setId(student.getExamId());
		sc.setStatus(1);
		bmkmxRepo.save(sc);
		
		//更新报考信息
		syncExam(student);
		
		return true;
	}
	
	/**
	 * 同步更新报考信息，艺术和体育类
	 * @param student
	 */
	public void syncExam(Student student){
		if(student.getSubjectType() != null){
			if(student.getSubjectType().equals("SPORT")){
				BKKSTY sport = new BKKSTY();
				sport.setId(student.getExamId());
				sport.setSportSigned(student.getSportSigned());
				if(student.getSportSigned() == 1){
					sport.setSportId(student.getSport().getId());
				}
				kstyRepo.save(sport);
			}
			else if(student.getSubjectType().equals("ART")){
				BKKSYS art = new BKKSYS();
				art.setId(student.getExamId());
				art.setArtStr(student.getSignString());
				ksysRepo.save(art);
			}
		}
	}
	
	/**
	 * 同步支付信息,如果支付成功或失败，向主数据库添加一条支付信息
	 * @param transRes 交易返回接口
	 * @param examId 报名号
	 * @throws SyncErrorException 
	 */
	@Transactional
	public boolean syncOrders(Order order,long zfdId,long zfmxId){
			boolean result = false;
			
					//插入zf_zfd
					ZFZFD zfd = new ZFZFD();
					zfd.setId(zfdId);
					zfd.setOrderId(order.getOrderId());
					zfd.setOrderName(order.getPayInfo());
					zfd.setShortDesc(order.getPayInfo());
					zfd.setMoney(order.getMoney());
					zfd.setStatus(order.getStatus());
					zfd.setPayType(1);
					zfd.setOrderUserNo(order.getExamId());
					zfd.setOrderDate(order.getCreatedDate());
					zfd.setPayDate(order.getPayDate());
					zfd.setPayDateStr(order.getTransDate());
					zfd.setCompleteDate(order.getPayDate());
					zfd.setCompleteDateStr(order.getTransDate());
					zfd.setMerId(order.getMerId());
					zfd.setChkValue(order.getChkValue());
					//zfdRepo.save(zfd);
					
					//同步zf_zfmx
					ZFZFMX zfmx = new ZFZFMX();
					zfmx.setPayOrder(zfd);
					zfmx.setId(zfmxId);
					zfmx.setPayType(order.getPayType());
					zfmx.setExamId(order.getExamId());
					zfmx.setPayFlag(1);
					zfmx.setPayInfo(order.getRemark());
					zfmxRepo.save(zfmx);
					
					
					result = true;
				return result;
	}
	
}
